<template>
    <PopList :title="'CesiumLab4'" :showButton="true" :link="'http://bjxbsj.cn'" @ok="addSceneObjects">
        <div class="images_bottom_content">
            <div class="images_servelocation">
                <label>服务地址</label>
                <input type="text" v-model="serverUrl" @blur="initNewList" @keydown.enter="initNewList">
            </div>
            <div class="images_servelocation">
                <label>查询内容</label><input type="text" v-model="searchValue" @blur="searchTargetList"
                    @keydown.enter="searchTargetList">
            </div>
            <div class="images_servelocation" v-if="informationShow">
                <label>影像url</label>
                <div class="images_servelocation_readonly">{{ serveUrl }}</div>
            </div>
            <div class="images_servelocation" v-if="informationShow">
                <label>最大级别</label>
                <div class="images_servelocation_readonly">{{ MaximumLevel }}</div>
            </div>
            <div class="images_servelocation" v-if="informationShow">
                <label>地理范围</label>
                <div class="images_servelocation_readonly">{{ geographicalScope }}</div>
            </div>
            <div class="images_lab_list">
                <div class="images_lab_son" v-for="(item, index) in newlist">
                    <label for="">{{ item[0].createTime.substring(0, 10) }}</label>
                    <div class="images_lab_son_list">
                        <div v-for="(i, ind) in item" class="images_img_lilist">
                            <div class="images_imgposition" @click="changeInformation(i, index, ind)"
                                :class="{ 'images_checkedactive': checkedactive == index && checkedInd == ind }">
                                <span v-show="iconIsShow === index && iconIndIsShow === ind ? true : false">{{ i.name
                                    }}</span>
                                <img :src="i.thumbnail ?? emptyImg" alt="">
                            </div>
                            <div class="images_onlineimageName" @mouseenter="handleMouseEnter(index, ind)"
                                @mouseleave="handleMouseLeave">
                                {{ i.name }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </PopList>
</template>

<script setup lang="ts">
import { searchMaxZindex } from "../../../scripts/general";
import { ESTerrainLayer } from "esobjs-xe2-plugin/dist-node/esobjs-xe2-plugin-main";
import { inject, onMounted, ref, watch } from 'vue';
import { SceneTree } from 'xbsj-xe2/dist-node/xe2';
import { get } from '../../../api/service';
import PopList from "../../../components/PopList.vue";
import { Message } from "earthsdk-ui"
import { XbsjEarthUi } from "../../../scripts/xbsjEarthUi";
const xbsjEarthUi = inject('xbsjEarthUi') as XbsjEarthUi
const sceneTree = inject('sceneTree') as SceneTree
const serveUrl = ref('')
const MaximumLevel = ref('')
const geographicalScope = ref('')
const checkedactive = ref()
const searchValue = ref('')
const informationShow = ref(false)
const itemName = ref('')
const rectangle = ref()
const iconIsShow = ref()
const newlist = ref()
const iconIndIsShow = ref()
const checkedInd = ref()
const serverUrl = ref()
const emits = defineEmits(['close', 'add']);
const emptyImg = require('../../../assets/common/terrain.png')
const handleMouseEnter = (index: number, ind: number) => {
    iconIsShow.value = index
    iconIndIsShow.value = ind
}
const handleMouseLeave = () => {
    iconIsShow.value = null
    iconIndIsShow.value = null
}
const addSceneObjects = () => {
    let maxZindex = searchMaxZindex(sceneTree, 'ESTerrainLayer');
    if (!serveUrl.value) Message.warning('请选择或者输入地址');
    else if (serveUrl.value) {
        const currentTreeItem = sceneTree.lastSelectedItem
        let newTreeItem
        if (!currentTreeItem) {
            newTreeItem = sceneTree.createSceneObjectTreeItem('ESTerrainLayer')
        } else if (currentTreeItem?.type === 'Folder') {
            newTreeItem = sceneTree.createSceneObjectTreeItem('ESTerrainLayer', undefined, currentTreeItem, 'Inner')
        } else {
            newTreeItem = sceneTree.createSceneObjectTreeItem('ESTerrainLayer', undefined, currentTreeItem, 'After')
        }
        if (!newTreeItem) return
        sceneTree.uiTree.clearAllSelectedItems()
        newTreeItem.uiTreeObject.selected = true
        if (!newTreeItem.sceneObject) return
        if (newTreeItem.sceneObject.typeName !== 'ESTerrainLayer') return
        const sceneObject = newTreeItem.sceneObject as ESTerrainLayer
        xbsjEarthUi.propSceneTree = newTreeItem
        newTreeItem.name = itemName.value;
        sceneObject.url = serveUrl.value
        sceneObject.rectangle = rectangle.value
        sceneObject.zIndex = maxZindex + 1
        emits("close")
    }
}
type ListDataItem = {

    "id": string,
    "name": string,
    "description": null,
    "storageType": string,
    "storageUri": string,
    "west": number,
    "east": number,
    "south": number,
    "north": number,
    "minzoom": number,
    "maxzoom": number,
    "contentType": string,
    "thumbnail": null,
    "url": null,
    "userId": null,
    "version": null,
    "subDomain": null,
    "createTime": string,
    "updateTime": null,
    "cors": null,
    "layerJson": null,
    "childResults": null,
    "bounds": {
        "east": number,
        "south": number,
        "north": number,
        "west": number
    },
    "level": {
        "maxlevel": number,
        "minlevel": number
    }

}
const groupBy = (array: ListDataItem[], f: Function) => {
    const groups: {
        [key: string]: ListDataItem[],
    } = {};
    array.forEach((item) => {
        const group = JSON.stringify(f(item));
        groups[group] = groups[group] || [];
        groups[group].push(item);
    });
    return Object.keys(groups).map((group) => {
        return groups[group];
    });
};
const sortClass = (sortData: ListDataItem[]) => {
    const sorted = groupBy(sortData, (item: ListDataItem) => {
        return item.createTime.substring(0, 10);
    });
    return sorted.reverse();
};
const changeInformation = (item: any, index: number, ind: number) => {
    checkedactive.value = index
    checkedInd.value = ind
    informationShow.value = true
    serveUrl.value = (`${serverUrl.value}/tile/terrain/${item.id}`)+ `${xbsjEarthUi.cesiumLabToken ? '?labtoken=' + xbsjEarthUi.cesiumLabToken : ''}`
    MaximumLevel.value = item.maxzoom
    geographicalScope.value = `${item.west.toFixed(4)}，${item.south.toFixed(4)}，${item.east.toFixed(4)}，${item.north.toFixed(4)}`
    itemName.value = item.name
    rectangle.value = [item.west, item.south, item.east, item.north]
}
const searchTargetList = () => {
    // const baseUrl = SceneObject.context.getStrFromEnv(serverUrl.value)
    get(`${serverUrl.value}/tile/terrain/list?key=${searchValue.value}&sort=desc&order=createTime`).then((res: any) => {
        if (res && res.data) {
            newlist.value = sortClass(res.data.list)
        }
    }).catch(error => {
        console.log(error);
        Message.error('请求地址错误')
        newlist.value = []
    })
}
watch(serverUrl, (val) => {
    xbsjEarthUi.cesiumLabUrl = val
},)
const initNewList = () => {
    get(`${serverUrl.value}/tile/terrain/list?sort=desc&order=createTime`).then((res: any) => {
        if (res && res.data) {
            // console.log(res);
            newlist.value = sortClass(res.data.list)
        }
    }).catch(error => {
        console.log(error);
        Message.error('请求地址错误')
        newlist.value = []
    })
}
onMounted(() => {
    serverUrl.value = xbsjEarthUi.cesiumLabUrl
    initNewList()
})
</script>